package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.BsJingqu;
import com.ruoyi.system.domain.BsQiye;
import com.ruoyi.system.domain.BsZhusu;
import com.ruoyi.system.domain.dto.BsZhusuExcelDto;
import com.ruoyi.system.mapper.BsQiyeMapper;
import com.ruoyi.system.mapper.BsZhusuMapper;
import com.ruoyi.system.service.BsJingquService;
import com.ruoyi.system.service.BsZhusuService;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @ClassName BsZhusuServiceImpl
 * @Author kenn
 * @Version 1.0.0
 * @Date 2023年10月17日 18:20:00
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class BsZhusuServiceImpl extends ServiceImpl<BsZhusuMapper, BsZhusu> implements BsZhusuService {

    private final BsJingquService jingquService;
    private final ISysDictTypeService dictTypeService;
    private final BsQiyeMapper qiyeMapper;

    @Override
    public TableDataInfo<BsZhusu> pageList(PageDomain pageDomain, String name) {
        LambdaQueryWrapper<BsQiye> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), BsQiye::getName, name);
        queryWrapper.in(BsQiye::getType, Arrays.asList("jiudian", "minsu"));
        queryWrapper.orderByDesc(BsQiye::getCreateTime);
        PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize());
        List<BsQiye> qiyeList = qiyeMapper.selectList(queryWrapper);
        PageInfo<BsQiye> pageInfo = new PageInfo<>(qiyeList);
        List<BsZhusu> zhusuList = buildRelationInfo(qiyeList);
        return new TableDataInfo<>(zhusuList, pageInfo.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveEntity(BsZhusu zhusu) {
        zhusu.setDelFlag(Constants.LOGIC_NOT_DELETE);
        BsQiye qiye = BeanUtil.copyProperties(zhusu, BsQiye.class);
        qiye.setDoorImg(zhusu.getImg());
        qiye.setApplyPhone(zhusu.getPhone());
        qiye.setApplyName(SecurityUtils.getLoginUser().getUser().getNickName());
        qiye.setAuditStatus("1");
        return qiyeMapper.insert(qiye) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEntity(BsZhusu zhusu) {
        BsQiye qiye = qiyeMapper.selectById(zhusu.getId());
        qiye.setName(zhusu.getName());
        qiye.setAddress(zhusu.getAddress());
        qiye.setType(zhusu.getType());
        qiye.setApplyPhone(zhusu.getPhone());
        qiye.setStatus(zhusu.getStatus());
        qiye.setBusinessLicenseImg(zhusu.getBusinessLicenseImg());
        qiye.setBusinessTime(zhusu.getBusinessTime());
        qiye.setAddressDetail(zhusu.getAddressDetail());
        return qiyeMapper.updateById(qiye) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        Assert.notNull(id, "主键id不能为空");
        return qiyeMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatusByQiyeId(Long qiyeId, String status) {
        Assert.notNull(qiyeId, "企业id不能为空");
        LambdaUpdateWrapper<BsZhusu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BsZhusu::getQiyeId, qiyeId);
        updateWrapper.set(BsZhusu::getStatus, status);
        return update(updateWrapper);
    }

    @Override
    public AjaxResult<?> export() {
        LambdaQueryWrapper<BsQiye> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BsQiye::getDelFlag, Constants.LOGIC_NOT_DELETE);
        queryWrapper.in(BsQiye::getType, Arrays.asList("jiudian", "minsu"));
        List<BsQiye> qiyeList = qiyeMapper.selectList(queryWrapper);
        List<BsZhusuExcelDto> exportList = new ArrayList<>();
        if (CollUtil.isNotEmpty(qiyeList)) {
            List<BsZhusu> zhusuList = buildRelationInfo(qiyeList);
            exportList = zhusuList.stream().map(i -> BeanUtil.copyProperties(i, BsZhusuExcelDto.class)).collect(Collectors.toList());
        }
        ExcelUtil<BsZhusuExcelDto> util = new ExcelUtil<>(BsZhusuExcelDto.class);
        return util.exportExcel(exportList, "住宿信息");
    }

    /**
     * 构建关联其他表字段信息/关联字典信息
     * @param qiyeList: 源数据集合
     * @return: void
     * @author: kenn
     * @date: 2023/10/18 14:24
     */
    public List<BsZhusu> buildRelationInfo(List<BsQiye> qiyeList) {
        List<BsZhusu> zhusuList = new ArrayList<>();
        if (CollUtil.isNotEmpty(qiyeList)) {
            List<Long> jingquIds = qiyeList.stream().map(BsQiye::getJingquId).collect(Collectors.toList());
            List<BsJingqu> jingquList = jingquService.listByIds(jingquIds);
            List<SysDictData> statusDictList = dictTypeService.selectDictDataByType(Constants.BUSINESS_STATUS);
            Map<Long, BsJingqu> jingquMap = null;
            Map<String, SysDictData> statusDictMap = null;
            if (CollUtil.isNotEmpty(jingquList)) {
                jingquMap = jingquList.stream().collect(Collectors.toMap(BsJingqu::getJingquId, Function.identity()));
            }
            if (CollUtil.isNotEmpty(statusDictList)) {
                statusDictMap = statusDictList.stream().collect(Collectors.toMap(SysDictData::getDictValue, Function.identity()));
            }
            for (BsQiye qiye : qiyeList) {
                BsZhusu zhusu = BeanUtil.copyProperties(qiye, BsZhusu.class);
                zhusu.setImg(qiye.getDoorImg());
                zhusu.setPhone(qiye.getApplyPhone());
                if (CollUtil.isNotEmpty(jingquMap)) {
                    zhusu.setJingquName(ObjectUtil.isNotNull(jingquMap.get(zhusu.getJingquId())) ? jingquMap.get(zhusu.getJingquId()).getJingquName() : "");
                }
                if (CollUtil.isNotEmpty(statusDictMap)) {
                    zhusu.setStatusName(ObjectUtil.isNotNull(statusDictMap.get(zhusu.getStatus())) ? statusDictMap.get(zhusu.getStatus()).getDictLabel() : "");
                }
                zhusuList.add(zhusu);
            }
        }
        return zhusuList;
    }

}
